package ait.mediabroadcast.mediaserver;

import org.teleal.cling.support.contentdirectory.AbstractContentDirectoryService;
import org.teleal.cling.support.contentdirectory.ContentDirectoryErrorCode;
import org.teleal.cling.support.contentdirectory.ContentDirectoryException;
import org.teleal.cling.support.contentdirectory.DIDLParser;
import org.teleal.cling.support.model.BrowseFlag;
import org.teleal.cling.support.model.BrowseResult;
import org.teleal.cling.support.model.DIDLContent;
import org.teleal.cling.support.model.SortCriterion;
import org.teleal.cling.support.model.container.Container;
import org.teleal.cling.support.model.item.Item;

import android.util.Log;

public class ContentDirectoryService extends AbstractContentDirectoryService {

	private final static String LOGTAG = "CDS";

	@Override
	public BrowseResult browse(String containerId, BrowseFlag browseFlag, String filter,
			long firstResult, long maxResults, SortCriterion[] orderby)
					throws ContentDirectoryException {

		DIDLContent didl = new DIDLContent();

		try {

			AndroidContentNode contentNode = AndroidContentTree.getNode(containerId);

			Log.d(LOGTAG, "container id: " + containerId);

			if (contentNode == null)
				return new BrowseResult("", 0, 0);

			if (contentNode.isItem()) {
				didl.addItem(contentNode.getItem());

				Log.d(LOGTAG, "return item: " + contentNode.getItem().getTitle());
			} else {
				if (browseFlag == BrowseFlag.METADATA) {
					didl.addContainer(contentNode.getContainer());

					Log.d(LOGTAG, "returning metadata of container: " + contentNode.getContainer().getTitle());

					return new BrowseResult(new DIDLParser().generate(didl), 1, 1);
				} else {
					for (Container container : contentNode.getContainer()
							.getContainers()) {
						didl.addContainer(container);

						Log.d(LOGTAG, "getting child container: " + container.getTitle());
					}
					for (Item item : contentNode.getContainer().getItems()) {
						didl.addItem(item);

						Log.d(LOGTAG, "getting child item: " + item.getTitle());
					}
					return new BrowseResult(new DIDLParser().generate(didl),
							contentNode.getContainer().getChildCount(),
							contentNode.getContainer().getChildCount());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ContentDirectoryException(
					ContentDirectoryErrorCode.CANNOT_PROCESS, e.toString());
		}

		return null;
	}


}
